package com.artpri.service.impl;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.artpri.service.ActionService;

/**
 * 面向controller提供dao层方法
 * @author ZhangSi
 *
 */
public class ActionServiceImpl extends BaseService implements ActionService {

	private Class<ActionServiceImpl> actionServiceClass = ActionServiceImpl.class;
	
	private String getMethodName(Class<?> classType) {
		String modelName = classType.getSimpleName();
		String methodName = "get" + modelName.substring(0, 1).toUpperCase() + modelName.substring(1) + "Dao";
		return methodName;
	}
	
	private Method getDaoMethod(Class<?> classType) throws NoSuchMethodException, SecurityException {
		return actionServiceClass.getMethod(getMethodName(classType));
	}
	
	private Object getDaoObject(Class<?> classType) throws Exception {
		return getDaoMethod(classType).invoke(this);
	}
	
	@Override
	@Transactional(readOnly=true)
	public Object get(Class<?> classType, Integer id) throws Exception {
		Object daoObject = getDaoObject(classType);
		return daoObject.getClass().getMethod("get", Class.class, Serializable.class).invoke(daoObject, classType, id);
	}

	@Override
	@Transactional
	public Integer save(Object o) throws Exception {
		Object daoObject = getDaoObject(o.getClass());
		return (Integer) daoObject.getClass().getMethod("save", Object.class).invoke(daoObject, o);
	}

	@Override
	@Transactional
	public void delete(Class<?> classType, Integer id) throws Exception {
		Object daoObject = getDaoObject(classType);
		daoObject.getClass().getMethod("delete", Class.class, Serializable.class).invoke(daoObject, classType, id);
	}

	@Override
	@Transactional
	public void delete(Object o) throws Exception {
		Object daoObject = getDaoObject(o.getClass());
		daoObject.getClass().getMethod("delete", Object.class).invoke(daoObject, o);
	}

	@Override
	@Transactional
	public void update(Object o) throws Exception {
		Object daoObject = getDaoObject(o.getClass());
		daoObject.getClass().getMethod("update", Object.class).invoke(daoObject, o);
	}

	@Override
	@Transactional(readOnly=true)
	public List<?> findAll(Class<?> classType) throws Exception {
		Object daoObject = getDaoObject(classType);
		return (List<?>) daoObject.getClass().getMethod("findAll", Class.class).invoke(daoObject, classType);
	}
}
